"""
文件上传API路由
演示文件上传、图片处理和静态文件服务
"""
import os
from fastapi import APIRouter, Depends, UploadFile, File, HTTPException, status
from fastapi.responses import FileResponse

from ..models.user import User
from ..schemas.upload import UploadResponse, ImageUploadResponse, UploadConfig
from ..dependencies import get_current_active_user
from ..utils.upload import (
    validate_upload_file, save_upload_file, compress_image,
    create_thumbnail, get_file_extension
)


router = APIRouter(prefix="/api/upload", tags=["文件上传"])


@router.get("/config", response_model=UploadConfig, summary="获取上传配置")
async def get_upload_config():
    """
    获取上传配置信息

    前端可以通过这个接口获取上传限制，用于客户端验证
    """
    from ..utils.upload import MAX_FILE_SIZE, ALLOWED_IMAGE_EXTENSIONS

    return UploadConfig(
        max_file_size=MAX_FILE_SIZE,
        allowed_extensions=list(ALLOWED_IMAGE_EXTENSIONS),
        upload_path="uploads"
    )


@router.post("/image", response_model=ImageUploadResponse, summary="上传图片")
async def upload_image(
    file: UploadFile = File(..., description="图片文件"),
    current_user: User = Depends(get_current_active_user)
):
    """
    上传图片文件

    功能特点：
    1. 文件类型和大小验证
    2. 自动图片压缩
    3. 生成缩略图
    4. 返回详细的文件信息

    需要管理员权限
    """
    # 验证文件
    await validate_upload_file(file, "image")

    # 保存文件
    file_path, filename = await save_upload_file(file, "images")

    # 获取文件信息
    file_size = os.path.getsize(file_path)

    # 压缩图片并获取尺寸
    dimensions = compress_image(file_path)
    width, height = dimensions if dimensions else (None, None)

    # 创建缩略图
    thumbnail_path = create_thumbnail(file_path)
    thumbnail_url = None
    if thumbnail_path:
        # 生成缩略图URL
        thumbnail_filename = os.path.basename(thumbnail_path)
        thumbnail_url = f"/uploads/images/{thumbnail_filename}"

    # 生成文件URL
    file_url = f"/uploads/images/{filename}"

    return ImageUploadResponse(
        filename=filename,
        original_filename=file.filename,
        file_path=file_path,
        file_url=file_url,
        file_size=file_size,
        content_type=file.content_type or "image/jpeg",
        width=width,
        height=height,
        thumbnail_url=thumbnail_url
    )


@router.post("/document", response_model=UploadResponse, summary="上传文档")
async def upload_document(
    file: UploadFile = File(..., description="文档文件"),
    current_user: User = Depends(get_current_active_user)
):
    """
    上传文档文件

    支持的文档类型：PDF, Word, Excel, PowerPoint

    需要管理员权限
    """
    # 验证文件
    await validate_upload_file(file, "document")

    # 保存文件
    file_path, filename = await save_upload_file(file, "documents")

    # 获取文件信息
    file_size = os.path.getsize(file_path)

    # 生成文件URL
    file_url = f"/uploads/documents/{filename}"

    return UploadResponse(
        filename=filename,
        original_filename=file.filename,
        file_path=file_path,
        file_url=file_url,
        file_size=file_size,
        content_type=file.content_type or "application/octet-stream"
    )


@router.delete("/file", summary="删除文件")
async def delete_file(
    file_path: str,
    current_user: User = Depends(get_current_active_user)
):
    """
    删除上传的文件

    Args:
        file_path: 文件路径（相对于uploads目录）

    需要管理员权限
    """
    # 安全检查：确保文件路径在uploads目录内
    if not file_path.startswith("uploads/"):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="无效的文件路径"
        )

    # 检查文件是否存在
    if not os.path.exists(file_path):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="文件不存在"
        )

    try:
        # 删除主文件
        os.remove(file_path)

        # 如果是图片，也删除缩略图
        if file_path.startswith("uploads/images/"):
            base_path, ext = os.path.splitext(file_path)
            thumbnail_path = f"{base_path}_thumb{ext}"
            if os.path.exists(thumbnail_path):
                os.remove(thumbnail_path)

        return {"message": "文件删除成功"}

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"删除文件失败: {str(e)}"
        )